/**
 * 
 */
package net.sf.rose.web.spring.servlet.handler;

import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.rose.common.BeanStore;
import net.sf.rose.jdbc.UserBean;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author fgg047
 * 
 */
@SuppressWarnings("deprecation")
public class FormHandler extends URLHandler {

	/**
	 * 
	 */
	private Method[] methods = null;

	/**
	 * 
	 */
	private Class<?> _class = null;

	/**
	 * 
	 */
	public FormHandler(Class<?> c) {
		methods = this.getClass().getMethods();
		_class = c;
	}

	/**
	 * 
	 */
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Object obj = null;
		String method = null;
		ModelAndView mv = null;
		boolean flag = false;
		Map<Object, Object> map = null;

		HttpSession session = request.getSession();
		obj = session.getAttribute("method");
		if (obj != null) {
			method = obj.toString();
			session.removeAttribute("method");
		}

		if (request.getContentType() != null
				&& request.getContentType().startsWith("multipart/form-data")) {
			map = this.getPostFileBean(request);
			if (method == null) {
				obj = request.getAttribute("method");
				if (obj != null && !obj.equals("")) {
					method = obj.toString();
				}
			}
		} else {
			if (method == null) {
				obj = request.getParameter("method");
				if (obj != null && !obj.equals("")) {
					method = obj.toString();
				}
			}
			obj = request.getParameter("code");
			if (obj != null) {
				map = this.getDecodePostBean(request);
			} else {
				map = this.getPostBean(request);
			}
		}

		// 根据类名和ID从Session中取数据类，如果没有则新建
		String key = null;
		Object val = null;
		Object bean = null;
		Class<?> c = _class;
		while (!c.getSuperclass().getSimpleName().equals("Object")) {
			c = c.getSuperclass();
		}
		key = c.getSimpleName();
		key = Character.toLowerCase(key.charAt(0)) + key.substring(1);
		val = map.get(key + "ID");
		if (val != null) {
			key = _class.getSimpleName().toLowerCase() + val;
			val = request.getSession().getAttribute(key);
		}
		if (val != null) {
			bean = val;
		} else {
			bean = _class.newInstance();
		}

		// 加载更新信息
		BeanStore bs = new BeanStore(bean);
		bs.setDatePattern(super.datePatten);
		Iterator<?> it = map.keySet().iterator();
		while (it.hasNext()) {
			key = it.next().toString();
			val = map.get(key);
			bs.setProperty(key, val);
		}

		// 执行处理方法
		try {
			if (method != null) {
				Method m = getMethod(method);
				if (m != null) {
					mv = (ModelAndView) m.invoke(this, request, response, bean);
					flag = true;
				}
			}
			if (!flag) {
				method = request.getMethod();
				if (method.equals("GET")) {
					mv = this.doGet(request, response, bean);
				} else if (method.equals("POST")) {
					mv = this.doPost(request, response, bean);
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
		}
		if (mv == null) {
			mv = new ModelAndView(getViewName());
		}
		return mv;
	}

	/**
	 * 
	 */
	public ModelAndView doGet(HttpServletRequest request,
			HttpServletResponse response, Object bean) {
		return new ModelAndView(getViewName());
	}

	/**
	 * 
	 */
	public ModelAndView doPost(HttpServletRequest request,
			HttpServletResponse response, Object bean) {
		return new ModelAndView(getViewName());
	}

	/**
	 * 
	 */
	private Method getMethod(String name) {
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].getName().equals(name)) {
				return methods[i];
			}
		}
		return null;
	}

	/**
	 * 
	 */
	protected Map<Object, Object> getPostBean(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		String key = null;
		Object val = null;
		Enumeration<?> en = request.getParameterNames();
		while (en.hasMoreElements()) {
			key = en.nextElement().toString();
			if (key.endsWith("list")) {
				// 多项选择如Checkbox以list结尾
				val = request.getParameterValues(key);
			} else {
				val = request.getParameter(key);
			}
			if (!val.toString().trim().equals("")) {
				map.put(key, val);
			} else {
				map.put(key, null);
			}
		}
		return map;
	}

	/**
	 * 
	 */
	protected Map<Object, Object> getDecodePostBean(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			String key = null;
			Object val = null;
			Enumeration<?> en = request.getParameterNames();
			while (en.hasMoreElements()) {
				key = en.nextElement().toString();
				val = request.getParameter(key);
				val = java.net.URLDecoder.decode(val.toString(), "UTF-8");
				if (!val.toString().trim().equals("")) {
					map.put(key, val);
				} else {
					map.put(key, null);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return map;
	}

	/**
	 * 
	 */
	protected Map<Object, Object> getPostFileBean(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			DiskFileUpload fu = new DiskFileUpload();
			//
			fu.setSizeMax(4194304);
			//
			fu.setSizeThreshold(4096);
			//
			String tempath = System.getenv("TEMP");
			if (tempath == null) {
				tempath = "c:/";
			}
			fu.setRepositoryPath(tempath);

			fu.setHeaderEncoding(request.getCharacterEncoding());

			//
			Iterator<?> it = fu.parseRequest(request).iterator();
			FileItem item = null;
			String key = null;
			String val = null;
			while (it.hasNext()) {
				item = (FileItem) it.next();
				if (item.isFormField()) {
					key = item.getFieldName();
					val = item.getString("UTF-8");
					if (!val.toString().trim().equals("")) {
						if (key.equals("method")) {
							request.setAttribute("method", val);
						} else {
							map.put(key, val);
						}
					} else {
						map.put(key, null);
					}
				} else {
					if (!item.getName().equals("")) {
						key = item.getFieldName();// 字段名
						String name = item.getName();// 文件名
						name = name.substring(name.lastIndexOf('\\') + 1,
								name.length());
						map.put(key.replaceFirst("Data", ""), name);// 文件名
						map.put(key, item.getInputStream());// 附件数据
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return map;
	}

	/**
	 * 
	 */
	protected UserBean getUser(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute("user");
		if (obj == null) {
			return null;
		}
		return (UserBean) obj;
	}

	/**
	 * 
	 */
	protected String getBaseURL(HttpServletRequest request) {
		String _url = request.getRequestURL().toString();
		String path = request.getContextPath();
		return _url.substring(0, _url.indexOf(path) + path.length()) + '/';
	}

}
